<?php
/**
 * Dirox Framework
 * Copyright (C) 2005 - 2007 Dirox / Synexser
 * 
 * All rights reserved.
 */

require_once ('DRX_UrlParser.php');

class DRX_MultiLanguage {
	static protected $_path;
	static protected $_domain;
	static protected $_language;
	static protected $_auth_lang;

	function initialize($lang,$auth_lang = array())
	{
		// Save the authorized languages
		self::$_auth_lang = $auth_lang;

		// Calculate needed domain and needed path
		$path = str_replace('/index.php','',$_SERVER['PHP_SELF']);
		self::$_domain = str_replace(
			array($path,'http://'),
			array('',''),
			APPLICATION_URL);
		if (substr(self::$_domain,0,1) != '.') { self::$_domain = '.'.self::$_domain; }
		self::$_path = $path.'/';
		
		if(!isset($_COOKIE['language']) || !in_array($_COOKIE['language'],self::$_auth_lang))
		{
			setcookie('language', $lang, time() + 3600*24*30, self::$_path, self::$_domain);
			self::$_language = $lang;
		}
		else
		{
			self::$_language = $_COOKIE['language'];
		}
	}

	function getLanguage()
	{
		return self::$_language;
	}

	function setLanguage($lang)
	{
		if ($lang != self::$_language and in_array($lang,self::$_auth_lang))
		{
			setcookie('language', $lang, time() + 3600*24*30, self::$_path, self::$_domain);
			self::$_language = $lang;
		}
	}

	function ShowLinkLanguage($arrLang) {
		$sLink = '';
		$root_path = str_replace('/index.php','',$_SERVER['PHP_SELF']);
		$objUrl = new DRX_UrlParser();
		$root_path = $objUrl->GetRootPath();
		$page_link = $objUrl->UrlToModrewrite($_SERVER['QUERY_STRING']);
		//get clean URL
		while (list($key, $val) = each($arrLang)) {
			$page_link = str_replace('setlang/'.$key, '', $page_link);
		}
		reset($arrLang);
		//show link
		while (list($key, $val) = each($arrLang)) {
			$val_href = $root_path.$page_link . '/setlang/'.$key;
			$sLink.= '<a href="'.str_replace('//','/',$val_href).'">'.$val.'</a>&nbsp;|&nbsp;';
		}
		unset($objUrl);
		return '|&nbsp;'.$sLink;
	}

	/**
	 * Load a given language file in the application.
	 * Launch an exception if the module cannot be loaded.
	 * Returns normally otherwise, or if the module is already loaded
	 *
	 * @param string the name of the module to load (which should correspond to the language file name in language/[code]/ folder
	 * @return nothing
	 * @throw DRX_Exception in case the module cannot be loaded
	 */
	function loadModule($moduleName)
	{
		$path = APPLICATION_DIR.'/language/'.self::$_language.'/'.$moduleName;
		if (is_file($path))
		{
			include_once($path);
		}
		else
		{
			throw new DRX_Exception("Cannot load module `$moduleName` (current language is `".self::$_language."`)",DRX_EX_LOAD_MODULE);
		}
	}
}
?>